<script src='http://protozoa.googlecode.com/svn/trunk/js/json.js'></script>
<script src='http://protozoa.googlecode.com/svn/trunk/js/functions.js'></script>
<script src='http://protozoa.googlecode.com/svn/trunk/js/functions.extra.js'></script>
<script src='http://protozoa.googlecode.com/svn/trunk/js/dom.js'></script>
<script src='http://protozoa.googlecode.com/svn/trunk/js/dom.event.js'></script>
<script src='http://protozoa.googlecode.com/svn/trunk/js/liveui.js'></script>
<script src='http://protozoa.googlecode.com/svn/trunk/js/liveui.extra.js'></script>
<script src='http://protozoa.googlecode.com/svn/trunk/js/window.js'></script>
<script src='http://protozoa.googlecode.com/svn/trunk/js/utils.js'></script>
<script src='http://protozoa.googlecode.com/svn/trunk/js/debug.js'></script>
<script src='http://protozoa.googlecode.com/svn/trunk/js/jsonrpc.js'></script>
<script src='http://blagotext.googlecode.com/svn/trunk/textarea2.js'></script>

<script>
var JSONRPC_PATH = '/jsonrpc2';
</script>


<title>jsonrpc2 test</title>
<style>
html {overflow-x:hidden;}
body {margin: 0; padding: 0;}
textarea {font: normal 10.5px monospace;  }
button, input {font: normal 11px Arial; }
textarea.input {width: 100%; height: 100px; font-size: 10px;}
textarea.output {width: 100%; height: 100%; }
input[name=path] {width: 100%;}
input[type=checkbox] {margin: 0; display: inline-block; vertical-align: middle; }

/* 
#out-html label { font: bold 11px Arial; display: block; }
#out-html input[type=text] { width: 100%; }
*/

#out-html label { font: bold 11px Arial; width:24%; display: inline-block; vertical-align:top; text-align:right; }
#out-html .teaser-checkbox label { width:auto; float:right; }
#out-html #edit-body-wrapper { clear:none; }
#out-html #edit-body-wrapper label {width: auto; float:left; }
#out-html fieldset { margin-top: 0.5em; background-color: #ddd; }
#out-html .form-submit { margin: 0.5em 0; }
#out-html ul { list-style-type: none; }
#out-html li { list-style-type: none; }
#out-html li label { width: auto; font-weight: normal; }
#out-html input[type=text] { width:75%; font: 11px Arial; }
#out-html .description { width:75%; float:right; font: 10px Arial; color: #999; zmargin-top: -5px; margin-bottom:10px;}
#out-html .form-item { clear:both; margin-top: 0.5em; }

#out-html .form-item .form-item { margin:0; display: inline-block; }
#out-html .form-item .form-item .description { width:auto; float:none; margin:0; margin-left: 25%; }
#out-html .form-item .form-item label {width: auto; }
#out-html .form-radios { display:inline-block; }

#out-html .form-item .form-item .form-item { display:inline-block; }
#out-html .form-item .form-item .form-item .description { width:auto; float:none; margin:0; padding:0; }
#out-html .form-item .form-radios .form-item {display:block; }

#out-html .form-radios label { font-weight: normal; }


#out-html input[type=radio] { margin:0; vertical-align:middle; }

#out-html select,
#out-html input { margin-top: -2px; }

#out-html textarea {width: 100%; height:100px; }

#out-html td, #out-html th { padding:0px 4px; empty-cells: show; }
</style>



<script>

//alert(JSON);

//if(window.set_message) window.alert = window.set_message;

window.onerror = function(e) {
//	alert(e);
	//e.stopPropagation();
	//e.preventDefault();
	return !1;
};

var get = function(x){return document.getElementById(x)};

var last_x;

var re_error = /^{[ \r\n\t]*("jsonrpc": *"2.0",[ \t\r\n]*)?"error":/m;


var check_error = function(x) {
	if((x !== undefined) && (x.indexOf('"error":') > 0)) {
		try {
			var y = JSON.parse(x);
			var e = y.error;
			var out = [];
			if(e.message.length < 50)
				out[out.length] = '<h2>' + e.message + '</h2>';
			var text = x || '';
			var file = '';
			//alert(x);
			x.replace(/ in (\/.*?\/([^\/]*)) on line (\d+)/, function($0, path, basename, lineno) {
				out[out.length] = '<i>' + basename + ':' + lineno + '</i><br>';
				return '.';
			});
			out[out.length] = '<pre>' + (typeof(e.data)=='string' ? e.data : e.message) + '</pre>';
			alert(out.join('').replace(/<\/(div|h[0-9])>/g, '\n').replace(/<\/?[^<>]+>/g, ''));
		}catch(e){}
	}
};

//var check_time = function(x) {
//	if(x && x.match(/"time":\s?([0-9.]+)/))
//		window.status = 'time: ' + RegExp.$1 + ' ms.';
//};

var get_result_only = function(x) {
	try {
		var y;
		x.replace(/(,\s*\n([ \t]*)")(result|error)"\s*:\s*/, function($0, $1, $2, $3){
			var r = RegExp.rightContext;
			rr=r.split($1);
			x=rr[0];
			if(x[0]=='"')
				x=x.replace(/\\[\\"rnt]/g, function($0){
					switch($0) {
						case '\\\\': return '\\';
						case '\\"':  return '"';
						case '\\n':  return '\n';
						case '\\r':  return '\r';
						case '\\t':  return '\t';
					}
				}).replace(/^"/, '').replace(/"$/, '');
				x = x.replace(new RegExp('^' + $2, 'mg'), '');
			return '';
			var n = r.lastIndexOf($1);
			if(n < 0)
				x = r.replace(/\n}\s*$/, '');
			else {
				x = r.substr(0, n + $1.length + 1);
			}
		});
	}catch(e){}
	return x;
};


var out_text = function(x) {
	var elem = get('out-text');
	if(elem.tagName == 'TEXTAREA')
		elem.value = x;
	else
		elem.innerHTML = x.replace(/</g, '&lt;');		
	elem.style.display='block';
	get('out-html').style.display = 'none';
}

var out_html = function(x) {
	try {
		var y = JSON.parse(x);
		y = y.result;

		if(y.rows) {
			var out = [];
			out[out.length] = '<table border=1 cellspacing=0 cellpadding=0 style="font:11px Arial">';
			
			if(y.columns)
				out[out.length] = '<tr><th>' + y.columns.join('<th>');
			
			for(var i=0; i<y.rows.length; ++i)
				out[out.length] = '<tr><td>' + y.rows[i].join('<td>');
			out[out.length] = '</table>';
			y = out.join('\n');
		}
		
		//if(typeof(y) != 'string')
		//	return out_text(x);
		get('out-text').style.display='none';
		var out = get('out-html');
		out.innerHTML = y;
		out.style.display = 'block';
		var xx = out.getElementsByTagName('form');
		for (var i = 0; i < xx.length; ++i)
			xx[i].setAttribute('target', 'fr-post');
	}catch(e){}
};



var out = mklate(10)(function(x){
	if(x===undefined) x = last_x; else last_x = x;
	check_error(x);				
	if(get('showHTML').checked) {
		//alert(x);
		out_html(x);
		return;
	}
	if(get('showResultOnly').checked)
		x = get_result_only(x);

	out_text(x);
});



var json;

window.jsonrpc_get_proxy = function(method){
	return function(){
		json = JSON.stringify({
			jsonrpc: '2.0',
			method: method,
			params: arguments.length > 1 ? Array.prototype.slice.apply(arguments) : arguments[0]
		});
	};
};


var req = new XMLHttpRequest;
var t0;
req.onreadystatechange = function(){
	switch(req.readyState) {
		case 1: t0 = +new Date; return;
		case 4: break;
		default: return;
	}
	var t = +new Date - t0;
	var status = 'client: ' + t;
	//window.status = status;
	window.setTimeout(function(){
		if(req.responseText.match(/"time":\s?([0-9.]+)/)) {
			//window.status = status + '; server: ' + RegExp.$1;
		}
	}, 40);
	out.call(0, req.responseText);
};

var run = function(form){
	set_message();
	//window.status = 'running...';
	//cl = '';
	var url = JSONRPC_PATH;
	if (form.path)
		url += form.path.value;

	//alert(url);
		
	//if(!/\?/.test(url))
	//	url += '?json_encode=jsonrpc';
	out.call(0, '');
	
	
	var l = form.json.selectionStart;
	var r = form.json.selectionEnd;
	json = form.json.value;

	json = json.replace(/\r\n/g, '\n');
	
	l = json.lastIndexOf('\n\n', l-1);
	r = json.indexOf('\n\n', r);
	
	if (l < 0) l = 0; else l = l + 2;
	if (r < 0) r = json.length;
	
	json = json.substr(l, r - l);
	
	
	json = json.replace(/^[ \r\n\t]+/,'').replace(/[ \r\n\t;]+$/, '');
	//alert(json);


	switch(true) {
		case (json=='') && (form.path.value!='') :
			//var req = new XMLHttpRequest;
			req.open('GET', url, false);
			req.send(null);
			out(req.responseText);
			//delete req;
			return;

		case (/\(/.test(json)) :
			var x = json.replace(/^[^\(\)]+/, 'jsonrpc_get_proxy("$&")');
			try { eval(x) } catch(e) { return alert(e.message) }
			break;


		case (/^[\w\[\]\.]+\s*/.test(json)) :
			//alert(new Function(json));
			json = (''+new Function(json)).replace(/^[^{]+{\n\s*/,'').replace(/;?\n}$/,'');
			json = json.replace(/^\s*([\w.]+)\s*=\s*/mg, '"$1", ');
			json = '[' + json.replace(/;$/gm, ',') + ']';
			json = JSON.stringify({
				method: 'Registry2.exec',
				params: eval(json)
			});
			url = JSONRPC_PATH;
			break;

	}
	
	
	url = new Url(url);

	if(!url.args.format)
		url.args.format = 'jsonrpc';
		
	//try{
		var xx=json.split('\n\n');

		
		for(var i=0; i<xx.length; ++i)
			xx[i] = JSON.stringify(eval('('+xx[i]+')'));
		json = xx.join('\n\n');

		
		req.open('POST', url, true);
		//req.setRequestHeader('Content-Type', 'text/plain; charset=UTF-8');
		t0 = +new Date;
		req.send(json);
		//var timer = window.setInterval(
	//}catch(e){
	//	alert('syntax error: '+e);
	//}
/*	
	return;
	
	try{
		var ret = eval('('+json+')');
		if(ret.error){
			alert('jsonrpc error: '+ret.error.message+'\n\n'+ret.error.data);
		}
		if(JSON && JSON.parse)
			try{
				JSON.parse(json);
				get('out').style.cssText='color:#0a5';
			}catch(e){
				out(json);
				get('out').style.cssText='color:#e60';
				alert(e);
				return;
			};
	}catch(e){
		get('out').style.cssText='color:#a05';
	}
*/	
};


var users;


/*
jsonrpc(function(){
	//alert(Test.random(100, 500));
	var search_users = function(pat) {
		var out = [];
		var ul = Drupal.user_list(pat);
		out[out.length] = ul;
		out[out.length] = Drupal.user_list(pat.substr(0, pat.length-1));
		return out;
	};
	var uu = search_users('kol');
	alert(dump(uu));
});
*/


/*
var search_users = function(pat){ return function(__return__){
	jsonrpc('Drupal.user_list', [pat], function(x){
		__return__(x);
	}
};
	search_users('d')(function(x){
		var uu = x;
		alert(dump(uu));
	});
*/



document.onkeydown = function(e){
	var x = [];
	if(e.ctrlKey) x='CTRL+';
	x+=e.which;
	if(x!='CTRL+13') return;
	if(e.target.id=='out'){
		var v = e.target.value;
		try{
			JSON.parse(v);
			e.target.style.cssText='color:#0a5';
		 }catch(ex){
	 		if(/[=\(\)]/.test(v.replace(/\\\\/g, '').replace(/\\"/g, '').replace(/"[^"]*"/g, '')))
	 			e.target.style.cssText='color:red; background-color:black';
	 		else
	 			try{		 		
			 		eval('('+e.target.value+')');
			 		e.target.style.cssText='color:#e60';
			 	}catch(ex){
			 		get('out').style.cssText='color:#c05';
			 	}
		 }
		return !1;
	}
	if(e.target.form){
		run(e.target.form);
		return !1;
	}
}
</script>

<body>
<div style='position:absolute;width:1px;height:1px;right:-1;bottom:-1'></div>

<table style='width:100%;height:100%;table-layout:fixed' zcellspacing=0 zcellpadding=0>
<col style='zwidth:40%'><col style='width:60%'>
<tr>
<td valign=top style="height:100%">
<!--<div style='width:30%;height:0;line-height:0;'></div>-->


<div zstyle='height:100%; zoverflow-y:auto'>
<div zstyle='height:100%; position:relative'>



<div style='position:absolute; top:0; left:0; width:40%; bottom:0; overflow-y:auto'>

<form onsubmit='run(this);return !1'>
	<input name='path' value=''>
<textarea id='t1' name='json' class='input' style='height:180px' wrap=off>
a = 10;
</textarea>
	<input type='submit' value='send'>
</form>

<hr>

<form onsubmit='try{run(this)}catch(e){alert(e)};return !1'>
	<input name='path' value=''>
<textarea name='json' class='input' id='t2' wrap=off>
</textarea>
	<input type='submit' value='send'>
</form>

<hr>

<form onsubmit='run(this);return !1'>
	<input name='path' value='?nocache'>
<textarea name='json' class='input' id='t3' wrap=off>
</textarea>
	<input type='submit' value='send'>
</form>

<button onclick='phpeditor()'>phpeditor</button>


</div></div></div>
<td valign=top style='width:60%'>
	<button onclick='(function(x){x.setAttribute("wrap", "wrap");x.style.overflowY="auto"})(get("out"))'>wrap</button>
	<button onclick='(function(x){x.setAttribute("wrap", "off");x.style.cssText=""})(get("out"))'>unwrap</button>
	<input id='showResultOnly' onclick='out()' type='checkbox'>
		<span style='display:inline-block;vertical-align:middle'>show result only</span>
	<input id='showHTML' onclick='out()' type='checkbox'>
		<span style='display:inline-block;vertical-align:middle'>show html</span>

	<div style='position:relative;zheight:100%;zwidth:100%;overflow-y:visible'>
		<div style='position:absolute;ztop:10px;zbottom:0;width:100%;'>
			<iframe id='fr-post' name='fr-post' style='height:100px;width:100%' src='about:blank'
				zonload='out(this.contentDocument.documentElement.textContent)'
			></iframe>
			<div id='out-html' style='display:none;height:500px;overflow:auto;background:#eee;margin-top:10px;padding:10px;'></div>
			<pre id='out-text' style='display:none;height:500px;width:100%;overflow:auto;background:#eee'></pre>
			<!--<textarea id='out' class='output' wrap='off' style='height:500px'></textarea>-->
		</div>
	</div>
</table>

<script>
(function(){
	var x = document.getElementById('t1');
	//var out = document.getElementById('out');
	x.setSelectionRange && x.setSelectionRange(22,22);
	window.setTimeout(function(){
		x.focus();
		//x.select();
	}, 200);
	out('');
})();

var phpeditor = function(){
	var div = document.createElement('div');
	div.className = 'liveui-removable liveui-draggable';
	div.style.cssText = 'position:absolute;top:50px;left:50px;width:300px;height:300px;border:1px solid black';
	document.body.appendChild(div);
};

//liveui('{F5}', function(){
//	get('out').value = '';
//});


liveui('{CTRL_/}', (function(){
	var inp;
	var event = mkevent();
	var elem;
	return function(ui){
		//elem = this;
		elem = ui.event.target;
		//alert(ui.event.target);
		var pos = get_position(elem);
		//alert(dump(pos));
		//return;
		if(!inp) {
			inp = document.createElement('input');
			inp.type = 'text';
			inp.style.cssText = 'position:absolute;z-index:9000;width:200px;border:5px solid #00f';
			document.body.appendChild(inp);
			event.add(inp, 'blur', function(e){
				inp.style.display = 'none';
			});
			event.add(inp, 'keypress', function(e){
				switch(e.keyCode) {
					case 27:
						inp.style.display = 'none';
						elem.focus();
						return;
					case 13:
						var re = new RegExp(inp.value, 'g');
						var m = elem.value.match(re);
						if(m) {
							inp.style.display = 'none';
							alert(m);
							elem.focus();
						}
				}
			});
		}
		inp.style.left = pos.left + 'px';
		inp.style.top = pos.bottom - inp.clientHeight + 'px';
		inp.style.display = 'block';
		inp.focus();
		inp.select();
	};
})());


(function() {
	var storage = localStorage;
	if (storage.jsonrpc_test) {
		var x;
		try {
			x = JSON.parse(storage.jsonrpc_test);
		} catch(e) {}
		if (x) {
			get('t1').value = x.t1;
			get('t2').value = x.t2;
			get('t3').value = x.t3;
		}
	}
	window.setTimeout(function(){
		window.setInterval(function(){
			localStorage.jsonrpc_test = '222';
			localStorage.jsonrpc_test = JSON.stringify({
				t1: get('t1').value,
				t2: get('t2').value,
				t3: get('t3').value
			});
		}, 200);
	}, 1000);
})();




</script>




</body>






